package com.cloudfun.campusshare.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.cloudfun.campusshare.common.constant.CashAdvanceHandleType;
import com.cloudfun.campusshare.common.constant.RoleType;
import com.cloudfun.campusshare.common.model.vo.*;
import com.cloudfun.campusshare.common.response.BaseResult;
import com.cloudfun.campusshare.common.response.BaseResultFactory;
import com.cloudfun.campusshare.common.security.AuthRequired;
import com.cloudfun.campusshare.service.CashAdvanceService;
import com.cloudfun.campusshare.util.AmountUtil;
import com.cloudfun.campusshare.util.DateUtil;
import com.cloudfun.campusshare.util.ExcelUtils;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/6/2 13:56
 * @description :
 */
@RestController
@RequestMapping("/v1/cashAdvance")
@Api(value = "提现")
@Validated
@Slf4j
//@AuthRequired
public class CashAdvanceController {
    @Autowired
    private CashAdvanceService cashAdvanceService;

    @GetMapping("/general")
    @ApiOperation(value = "查询提现列表统计数据", notes = "查询提现列表统计数据")
    public BaseResult getGeneral() {
        return BaseResultFactory.produceSuccess(cashAdvanceService.getGeneralData());
    }

    @GetMapping("/launch")
    @ApiOperation(value = "发起提现", notes = "发起提现")
    public BaseResult launchCashAdvance(){
        cashAdvanceService.launchCashAdvance();
        return BaseResultFactory.produceSuccess();
    }

    @GetMapping("/list")
    @ApiOperation(value = "提现列表", notes = "提现列表")
    public BaseResult queryCashAdvanceList(Pageable pageable, @ApiParam(value = "关键字") @RequestParam(required = false)String keyword,
                                                                @ApiParam(value = "状态") @RequestParam(required = false) Set<Integer> status,
                                                                @ApiParam(value = "开始时间") @RequestParam(required = false)String startTime,
                                                                @ApiParam(value = "结束时间") @RequestParam(required = false)String endTime){
        return BaseResultFactory.produceSuccess(cashAdvanceService.queryCashAdvanceList(pageable, keyword, status, startTime, endTime));
    }

    @GetMapping("/list/export")
    @ApiOperation(value = "导出提现列表", notes = "导出提现列表")
    public BaseResult exportCashAdvanceList(@ApiParam(value = "id集合") @RequestParam(required = false) Set<String> ids,
                                            @ApiParam(value = "关键字") @RequestParam(required = false)String keyword,
                                            @ApiParam(value = "状态") @RequestParam(required = false) Set<Integer> status,
                                            @ApiParam(value = "开始时间") @RequestParam(required = false)String startTime,
                                            @ApiParam(value = "结束时间") @RequestParam(required = false)String endTime,
                                            @ApiParam(value = "是否导出全部") @RequestParam(required = false)Boolean all,
                                            HttpServletResponse response) throws IOException {
        List<CashAdvanceListExportVO> cashAdvanceListExportVOS = cashAdvanceService.exportCashAdvanceList(ids, keyword, status, startTime, endTime, all);
        ExcelUtils.exportExcel(cashAdvanceListExportVOS,null,"提现审核",CashAdvanceListExportVO.class,"提现审核",response);
        return BaseResultFactory.produceSuccess();
    }

    @GetMapping("/detail/export/{cashAdvanceId}")
    @ApiOperation(value = "导出提现详情", notes = "导出提现详情")
    public BaseResult exportCashAdvanceDetail(@PathVariable String cashAdvanceId,
                                            HttpServletResponse response) throws IOException {
        CashAdvanceDetailExportVO cashAdvanceDetailExportVO = cashAdvanceService.exportCashAdvanceDetail(cashAdvanceId);
        List<DailyBalanceListVO> elements = cashAdvanceService.getDailyBalanceDataList(cashAdvanceId);
        List<DailyBalanceListExportVO> collect = elements.stream()
                .map(x -> {
                    DailyBalanceListExportVO dailyBalanceListExportVO = new DailyBalanceListExportVO();
                    dailyBalanceListExportVO.setBalanceAccountNo(x.getBalanceAccountNo());
                    dailyBalanceListExportVO.setBillDate(DateUtil.customTransfer(x.getBillDate(), "yyyy-MM-dd"));
                    dailyBalanceListExportVO.setJournalAmount(x.getJournalAmount());
                    dailyBalanceListExportVO.setDiscountPrice(x.getDiscountPrice());
                    dailyBalanceListExportVO.setSettlementAmount(x.getSettlementAmount());
                    return dailyBalanceListExportVO;
                }).collect(Collectors.toList());

        List<Map<String,Object>> param = Lists.newArrayList();
        Map<String,Object> map = new HashMap<>();
        map.put("title",new ExportParams(null,"总览"));
        map.put("entity",CashAdvanceDetailExportVO.class);
        map.put("data",Lists.newArrayList(cashAdvanceDetailExportVO));
        param.add(map);
        Map<String,Object> mapForDaily = new HashMap<>();
        mapForDaily.put("title",new ExportParams(null,"单日结算"));
        mapForDaily.put("entity",DailyBalanceListExportVO.class);
        mapForDaily.put("data",collect);
        param.add(mapForDaily);
        ExcelUtils.exportExcel(param,cashAdvanceDetailExportVO.getCashAdvanceNo(),response);
        return BaseResultFactory.produceSuccess();
    }

    @GetMapping("/detail/{cashAdvanceId}")
    @ApiOperation(value = "提现详情", notes = "提现详情")
    @AuthRequired(role = {RoleType.ADMIN,RoleType.OPERATIONAL_MERCHANT})
    public BaseResult queryCashAdvanceDetail(@PathVariable String cashAdvanceId){
        return BaseResultFactory.produceSuccess(cashAdvanceService.queryCashAdvanceDetail(cashAdvanceId));
    }

    @GetMapping("/dailyBalance/list/{cashAdvanceId}")
    @ApiOperation(value = "每日结算列表", notes = "每日结算列表")
    public BaseResult queryDailyBalanceList(Pageable pageable,@PathVariable String cashAdvanceId){
        return BaseResultFactory.produceSuccess(cashAdvanceService.getDailyBalanceData(pageable,cashAdvanceId));
    }

    @GetMapping("/account/confirm")
    @ApiOperation(value = "帐号确认", notes = "帐号确认")
    public BaseResult confirmAccount(){
        return BaseResultFactory.produceSuccess(cashAdvanceService.confirmAccount());
    }

    @GetMapping("/count/groupBy/status")
    @ApiOperation(value = "分组状态查询", notes = "分组状态查询")
    public BaseResult groupByStatus(){
        return BaseResultFactory.produceSuccess(cashAdvanceService.countGroupByStatus());
    }

    @PostMapping("/auditing")
    @ApiOperation(value = "提现审核", notes = "提现审核")
    @AuthRequired(role = RoleType.ADMIN)
    public BaseResult handleRequest(@RequestBody CashAdvanceHandleVO cashAdvanceHandleVO){
        cashAdvanceService.handleCashAdvanceRequest(cashAdvanceHandleVO);
        return BaseResultFactory.produceSuccess();
    }


}
